<!-- AI喷淋工作模板配置页面 -->
<template>
  <a-modal
    :width='1000'
    :visible='visible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible='updateVisible'
    @ok='save'
  >
    <a-form
      ref='form'
      :model='form'
      :rules='rules'
      :label-col='{ md: { span: 6 }, sm: { span: 24 } }'
      :wrapper-col='{ md: { span: 18 }, sm: { span: 24 } }'
    >
      <!-- 基本信息 -->
      <a-row :gutter="16">
        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label='模板名称:' name='configName'>
            <a-input v-model:value='form.configName' placeholder='请输入配置名称' style="width: 400px;" allow-clear autocomplete='off' />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24" :xs="24"></a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label='所属牧场:' name='farmId'>
            <a-select
              v-model:value="form.farmId"
              placeholder="请选择所属牧场"
              allow-clear
            >
              <a-select-option v-for="item in farmList" :key="item.farmId">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
         <a-col :md="12" :sm="24" :xs="24"></a-col>
      </a-row>

      <!-- 传统工作参数 -->
      <a-divider orientation="left">传统工作参数<span style="font-size: 10px;">(不考虑有牛无牛、一般手动启动或者系统若机自动启动)</span></a-divider>
      <div class="parameter-section">
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='持续喷水:' name='continuousSpray'>
              <a-input-number v-model:value='configForm.offline_params.duration' placeholder='请输入持续喷水时间(秒)' :min="0" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='间隔喷水(秒):' name='intervalSpray'>
              <a-input-number v-model:value='configForm.offline_params.interval' placeholder='请输入间隔喷水时间(秒)' :min="0" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- AI喷淋工作模板 -->
      <a-divider orientation="left">AI喷淋工作模板</a-divider>
      <div class="parameter-section">
        <a-row :gutter="16">
          <a-col :md="22" :sm="24" :xs="24">
            <a-form-item label='喷头最大工作比 (%):' name='maxWorkRatio'>
              <a-input v-model:value='configForm.level_open_max_rate' placeholder='请输入' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="24" :xs="24">
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :md="22" :sm="24" :xs="24">
            <a-form-item label='档位判断模式:' name='gearMode'>
              <a-select v-model:value="configForm.threshold_type" placeholder="请选择档位判断模式">
                <a-select-option :value="1">温湿度模式</a-select-option>
                <a-select-option :value="2">THI模式</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="24" :xs="24"></a-col>
        </a-row>

        <!-- 联动参数 -->
        <a-row>
          <a-col :span="22">
            <a-form-item label='联动参数:' :wrapper-col="{ span: 24 }" style="margin-bottom: 0">
              <div class="gear-table-container">
                <div class="gear-table-header">
                  <div class="gear-cell">档位</div>
                  <div class="gear-cell">开启温度</div>
                  <div class="gear-cell">持续喷水</div>
                  <div class="gear-cell">间隔喷水</div>
                  <div class="gear-cell">模式
                    <a-button type="link" style="padding: 0 0 0 5px" @click="showModeHelp">
                      <question-circle-outlined />
                    </a-button>
                  </div>
                  <div class="gear-cell">操作</div>
                </div>
                <div v-for="(gear, index) in configForm.level_params" :key="index" class="gear-table-row">
                  <div class="gear-cell">{{ gear.index }}</div>
                  <div class="gear-cell">
                    <a-input-number v-model:value="gear.threshold" :min="0" style="width: 80px" />
                  </div>
                  <div class="gear-cell">
                    <a-input-number v-model:value="gear.duration" :min="0" style="width: 80px" />
                  </div>
                  <div class="gear-cell">
                    <a-input-number v-model:value="gear.interval" :min="0" style="width: 80px" />
                  </div>
                  <div class="gear-cell">
                    <div class="gear-cell">
                      <div style="display: flex; align-items: center; width: 100%;">
                        <a-select v-model:value="gear.work_mode" style="width: 80px">
                          <a-select-option :value="1">一般</a-select-option>
                          <a-select-option :value="2">高效</a-select-option>
                        </a-select>
                      </div>
                    </div>
                  </div>
                  <div class="gear-cell">
                    <a-button type="text" danger @click="configForm.level_params.splice(index, 1)">
                      <delete-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div style="margin-top: 10px">
                <a-button type="primary" @click="addGear">
                  <plus-outlined /> 新增档位
                </a-button>
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="2"></a-col>
        </a-row>
      </div>

      <!-- 智能工作参数 -->
      <a-divider orientation="left">智能工作参数</a-divider>
      <div class="parameter-section">
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='温度(°C):' name='temperature'>
              <a-input-number v-model:value='configForm.emergency_params.threshold' placeholder='请输入温度' :min="0" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='持续喷水(秒):' name='smartContinuousSpray'>
              <a-input-number v-model:value='configForm.emergency_params.duration' placeholder='请输入持续喷水时间' :min="0" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='间隔喷水(秒):' name='smartIntervalSpray'>
              <a-input-number v-model:value='configForm.emergency_params.interval' placeholder='请输入间隔喷水时间' :min="0" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='全开分组:' name='fullOpenGroup'>
              <a-input v-model:value='configForm.emergency_params.all_open_group' placeholder='请输入' allow-clear />
              <div class="form-hint">注: 最多分6组</div>
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 高湿即停 -->
      <a-divider orientation="left">高湿即停<span style="font-size: 10px;">(一但达到设定指标自动停止喷淋工作)</span></a-divider>
      <div class="parameter-section">
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='开启:' name='highHumidityStop'>
              <a-checkbox v-model:checked="configForm.high_humidity_params.enable"></a-checkbox>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='湿度(%RH):' name='humidityThreshold'>
              <a-input-number v-model:value='configForm.high_humidity_params.threshold' placeholder='请输入湿度阈值' :min="0" :max="100" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 高效模式延迟设置 -->
      <a-divider orientation="left">高效模式延迟设置<span style="font-size: 10px;">(喷淋高效工作时设置延迟时间，即牛来多久后喷淋才开启)</span></a-divider>
      <div class="parameter-section">
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='开启:' name='efficientModeDelay'>
              <a-checkbox v-model:checked="configForm.efficient_mode_params.enable"></a-checkbox>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='延迟时间(秒):' name='delayTime'>
              <a-input-number v-model:value='configForm.efficient_mode_params.delay_duration' placeholder='请输入延迟时间' :min="0" :step="0.1" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
      </div>
      <!-- 高效模式延迟设置 -->
      <a-divider orientation="left">分组轮询<span style="font-size: 10px;">(摄像头分析分组轮询参数)</span></a-divider>
      <div class="parameter-section">
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='开启:' name='analysisGroupEnable'>
              <a-checkbox v-model:checked="configForm.analysis_group_params.enable"></a-checkbox>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='轮流分组数量:' name='analysisGroupTurnsgroup'>
              <a-input-number v-model:value='configForm.analysis_group_params.turns_group' placeholder='请输入轮流分组数量' :min="0" :step="1" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label='轮流工作时长(秒):' name='analysisGroupTurnsDuration'>
              <a-input-number v-model:value='configForm.analysis_group_params.turns_duration' placeholder='请输入轮流工作时长' :min="0" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
           <a-form-item label='轮流间隔时长(秒):' name='analysisGroupTurnsInterval'>
              <a-input-number v-model:value='configForm.analysis_group_params.turns_interval' placeholder='请输入轮流间隔时长' :min="0" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
      </div>

    </a-form>
      <!-- 模式选择说明弹窗 -->
      <a-modal
        v-model:visible="modeHelpVisible"
        title="模式选择说明"
        :footer="null"
        :width="400"
        @cancel="modeHelpVisible = false"
      >
        <div class="mode-help-content">
          <div class="mode-item">
            <div class="mode-icon general-icon"><file-outlined /></div>
            <div class="mode-info">
              <h3>一般</h3>
              <p>牛走后，必须等到下一个周期再工作。</p>
            </div>
          </div>
          <div class="mode-item">
            <div class="mode-icon efficient-icon"><rocket-outlined /></div>
            <div class="mode-info">
              <h3>高效</h3>
              <p>牛来喷，牛走停，无论在不在周期周期。</p>
            </div>
          </div>
        </div>
      </a-modal>
    </a-modal>
</template>

<script>
import { DeviceAiEdgeSprayConfigApi } from '@/api/property/aiedgecomputer/DeviceAiEdgeSprayConfigApi';
import { DeviceAiEdgeFarmApi } from '@/api/property/aiedgecomputer/DeviceAiEdgeFarmApi';
import { PlusOutlined, DeleteOutlined, FileOutlined, RocketOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

export default {
  name: 'DeviceManagerdeviceAiedgeComputerHazzxConfigEdit',
  // 在components中添加图标组件
  components: {
    PlusOutlined,
    DeleteOutlined,
    FileOutlined,  // 添加这行
    RocketOutlined, // 添加这行
    QuestionCircleOutlined // 添加这行

  },
  emits: ['done', 'update:visible'],
  props: {
    visible: Boolean,
    data: Object,
    scene : String,
    placeId : Number
  },
  // 在data()中添加模态框可见性控制
  data() {
    return {
      // 表单数据
      form: {
        configName: '',
        farmId: undefined,
        configType: 1,
        defaultt: 0,
        farmDefault: 0,
        config: ''
      },
      // 配置表单数据
      configForm: {
        // 传统工作参数
        offline_params: {
          duration: 30,
          interval: 180,
          heart_time: 60
        },
        // AI喷淋工作模板
        threshold_type: 1, // 1温湿度 2THI
        level_open_max_rate : 0,
        level_params: [],
        // 智能工作参数
        emergency_params: {
          threshold: 40,
          duration: 30,
          interval: 60,
          all_open_group : 0
        },
        // 高湿即停
        high_humidity_params: {
          enable: false,
          threshold: 0
        },
        // 高效模式延迟设置
        efficient_mode_params: {
          enable: true,
          is_delay: true,
          delay_duration: 0.1
        },
        analysis_group_params : { //摄像头分组轮询参数
          enable : false,
          turns_group : 1,
          turns_duration : 0,
          turns_interval : 0
        }
      },
      // 表单验证规则
      rules: {
        configName: [{ required: true, message: '请输入配置名称', type: 'string', trigger: 'blur' }],
        farmId: [{ required: false, message: '请选择所属牧场', trigger: 'change' }]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 牧场列表
      farmList: [],
      modeHelpVisible: false, // 添加这行
    };
  },
  created() {
    // 当弹窗打开时，获取牧场列表
    this.fetchFarmList();
    if (this.data) {
      this.form = Object.assign({}, this.data);
      if (this.form.config) {
        try {
          const parsedConfig = JSON.parse(this.data.config);
          for (const key in parsedConfig) {
            if (parsedConfig.hasOwnProperty(key)) {
              this.configForm[key] = parsedConfig[key];
            }
          }
          console.log(this.configForm);
        } catch (e) {
          console.error('解析配置内容失败:', e);
        }
      }
      this.isUpdate = true;
    } else {
      // 重置表单
      this.resetForm();
      this.isUpdate = false;
    }  
  },
  methods: {

    showModeHelp() {
      this.modeHelpVisible = true;
    },
    /**
     * 获取牧场列表
     */
    async fetchFarmList() {
      try {
        const response = await DeviceAiEdgeFarmApi.list({});
        this.farmList = (response ? response.data : null) || [];
      } catch (error) {
        console.error('获取牧场列表失败:', error);
        this.$message.error('获取牧场列表失败');
      }
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.form = {
        configName: '',
        farmId: undefined,
        configType: 1,
        defaultt: 0,
        farmDefault: 0,
        config: ''
      };
      
      this.configForm = {
        // 传统工作参数
        offline_params: {
          duration: 30,
          interval: 180,
          heart_time: 60
        },
        // AI喷淋工作模板
        threshold_type: 1, // 1温湿度 2THI
        level_open_max_rate : 0,
        level_params: [],
        // 智能工作参数
        emergency_params: {
          threshold: 40,
          duration: 30,
          interval: 60,
          all_open_group : 0
        },
        // 高湿即停
        high_humidity_params: {
          enable: false,
          threshold: 0
        },
        // 高效模式延迟设置
        efficient_mode_params: {
          enable: true,
          is_delay: true,
          delay_duration: 0.1
        },
        analysis_group_params : { //摄像头分组轮询参数
          enable : false,
          turns_group : 1,
          turns_duration : 0,
          turns_interval : 0
        }
      };
    },

    /**
     * 添加档位
     */
    addGear() {
      const newIndex = this.configForm.level_params.length > 0 
        ? this.configForm.level_params[this.configForm.level_params.length - 1].index + 1 
        : 1;
      
      this.configForm.level_params.push({
        index: newIndex,
        threshold: 25,
        duration: 20,
        interval: 480,
        work_mode: 2
      });
    },

    /**
     * 保存和编辑
     */
    async save() {
      try {
        // 校验表单
        await this.$refs.form.validate();

        // 修改加载框为正在加载
        this.loading = true;

        // 准备提交的数据
        const submitData = { ...this.form };
        
        // 直接使用configForm作为配置内容
        if (this.configForm.efficient_mode_params.delay_duration > 0) {
          this.configForm.efficient_mode_params.is_delay = true;
        }
        submitData.config = JSON.stringify(this.configForm);

        let result = null;

        // 执行编辑或修改
        if (this.isUpdate) {
          if (this.scene == 'place') {
            submitData.placeId = this.placeId;
            result = await DeviceAiEdgeSprayConfigApi.copyEdit(submitData);
          } else {
            result = await DeviceAiEdgeSprayConfigApi.editRemote(submitData);
          }
        } else {
          result = await DeviceAiEdgeSprayConfigApi.addRemote(submitData);
        }

        // 移除加载框
        this.loading = false;

        // 提示数据同步中
        message.loading('操作成功，数据同步中...', 5);

        // 如果是新增，则form表单置空
        if (!this.isUpdate) {
          this.resetForm();
        }

        // 延迟3秒后关闭弹窗
        await new Promise(resolve => setTimeout(resolve, 5000));

        // 关闭弹框，通过控制visible的值，传递给父组件
        this.updateVisible(false);

        // 触发父组件done事件
        this.$emit('done');
      } catch (error) {
        this.loading = false;
        console.error('保存失败:', error);
      }
    },

    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }
  }
};
</script>

<style scoped>
.parameter-section {
  padding: 0 16px 16px;
}

.form-hint {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.gear-table-container {
  border: 1px solid #f0f0f0;
  border-radius: 2px;
  width: 100%;
}

.gear-table-header {
  display: flex;
  background-color: #fafafa;
  font-weight: 500;
  border-bottom: 1px solid #f0f0f0;
}

.gear-table-row {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.gear-table-row:last-child {
  border-bottom: none;
}

.gear-cell {
  flex: 1;
  padding: 12px 8px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
.mode-help-content {
  padding: 10px 0;
}

.mode-item {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

.mode-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
}

.general-icon {
  background-color: #e6f7ff;
  color: #1890ff;
}

.efficient-icon {
  background-color: #f6ffed;
  color: #52c41a;
}

.mode-info h3 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.mode-info p {
  margin: 0;
  color: #666;
}
</style>
